
import Vue from "vue";
const directive= ([el, binding, vnode, oldVnode], isCreated) => {
    let context = vnode.context,
        bind = binding.value,
        permission;
    let key = '';
    let label = '';
    if(!bind) return;
    if(typeof bind === 'string') {
        key = bind;
    }else {
        key = bind.key;
        label = bind.label
    }
    if(!key) {
        return;
    }

    permission = context.$store.getters["account/getPermissionJudgeHandle"](
        key
    );
    if(isCreated) {
        // 开始绑定的时候添加log
        // 主要是打印出按钮权限 方便添加权限

        try{
            el.setAttribute("data-permissionControl", key);
            let permissionLog = JSON.parse(localStorage.permissionLog || null) || {};
            let path = context.$route.path + "_"+ context.$route.matched[0].meta.title;
            let obj = permissionLog[path] || {};
            obj[key] = label;

            permissionLog[path] = obj;

            localStorage.permissionLog = JSON.stringify(Object.assign({},  permissionLog));

        }catch(e) {
            console.log(e);
        }
    }

    // 不使用权限
    if(bind?.disabled) {
        return;
    }

    if(bind.able) {
        // 有这个字段才启用权限控制
        if(!permission) {
            el.setAttribute("style", "display:none");
            el.setAttribute("data", key);
        }
    }

};

Vue.directive("permission", {
    update: (...reset) => directive(reset),
    bind: (...reset) => {
        directive(reset, true)
    }
});
